package com.duojuhe.websocket.socket;

import com.duojuhe.websocket.message.MessageHandle;
import lombok.extern.slf4j.Slf4j;
import javax.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean;

/**
 * Socket配置
 *
 */
@Configuration
@EnableWebSocket
@Slf4j
public class SocketConfig implements WebSocketConfigurer {
    @Resource
    private SocketInterceptor socketInterceptor;
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) {
        webSocketHandlerRegistry.addHandler(myHandler(), "/webSocket")
                .addInterceptors(socketInterceptor)
                .setAllowedOrigins("*");
    }

    @Bean
    public WebSocketHandler myHandler() {
        return new MessageHandle(1000);
    }

    @Bean
    public ServletServerContainerFactoryBean createServletServerContainerFactoryBean() {
        Integer bufferSize = 512000;
        Long sendTimeout = 3000L;
        ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();
        container.setMaxTextMessageBufferSize(bufferSize);
        container.setAsyncSendTimeout(sendTimeout);
        log.info("set server side socket buffer size to {}, send timeout = {}", bufferSize, sendTimeout);
        return container;
    }
}
